<template>
  <view class="schedule-container">
	<!-- 公共头部 -->
	<headerPublic style="position: fixed;" title="日程" />
    <!-- 日历部分 -->
	<view class="calendar-section outbottom" @touchstart="onTouchStart" @touchend="onTouchEnd">
      <!-- 年月选择 -->
      <view class="month-picker">
        <image @click="prevMonth" src="/static/arrow-left.png" class="arrowImg"></image>
        <view class="uni-dropdown" @click="toggleDropdown">
          <text class="el-dropdown-link">
            {{ currentYear }}年{{ currentMonthIndex + 1 }}月<i class="el-icon-arrow-down el-icon--right"></i>
          </text>
          <view class="uni-dropdown-menu" v-if="isDropdownVisible">
            <view class="uni-dropdown-item" v-for="(month, index) in months" :key="index" @click="changeMonth(index)">
              {{ month }}
            </view>
          </view>
        </view>
        <image @click="nextMonth" src="/static/arrow-right.png" class="arrowImg"></image>
      </view>

      <!-- 星期表头 -->
      <view class="week-header">
        <text v-for="(day, index) in weekDays" :key="index">{{ day }}</text>
      </view>

      <!-- 日历日期格子 - 带过渡动画 -->
      <view class="calendar-days-wrapper">
        <transition :name="transitionName">
          <view class="calendar-days" :key="calendarKey">
            <view v-for="(week, weekIndex) in calendarDays" :key="weekIndex" class="calendar-week">
              <view v-for="(day, dayIndex) in week" :key="dayIndex" class="calendar-day" :class="{
                'is-today': isToday(day),
                'has-event': hasEvent(day),
                'is-other-month': !isCurrentMonthDay(day),
                'is-selected': isSelectedDay(day)
              }" @click="!isCurrentMonthDay(day) ? null : selectDay(day)">
                <text class="date-number">{{ day.date }}</text>
                <text v-if="hasEvent(day)" class="event-marker"></text>
              </view>
            </view>
          </view>
        </transition>
      </view>
    </view>

    <!-- 日程详情部分 -->
    <view class="schedule-details-section" v-if="selectedDay">
      <view style="margin-bottom: 10px;">
        <text style="font-size: 30px;color: #2D75D7;margin-right:10px">{{ selectedDay.date }}</text>
        <text style="font-size: 15px;color: #555555;">{{ selectedDay.year + '.' + (selectedDay.month + 1) }}&nbsp;星期{{
          getWeekday(selectedDay) }}</text>
      </view>
      <view v-if="selectedDay.events && selectedDay.events.length > 0">
        <view class="schedule-event" v-for="(event, index) in selectedDay.events" :key="index"
          @click="clickEvent(event.id)">
          <view class="event-time-wrapper">
            <view class="event-start-time">{{ event.startTime }}</view>
            <view class="event-end-time">{{ event.endTime }}</view>
          </view>
          <view class="event-content">{{ event.content }}</view>
        </view>
      </view>
      <view v-else>
        <text>暂无日程</text>
      </view>
    </view>

    <view v-else class="schedule-details-section">
      <text>请选择一个日期查看日程</text>
    </view>

    <button class="addNew" @click="addNew">新建</button>
  </view>
</template>

<script>
import {
  scheduleList
} from '@/api/schedule.js'
export default {
  name: 'schedule',
  data() {
    return {
      currentYear: new Date().getFullYear(),
      currentMonthIndex: new Date().getMonth(),
      currentMonth: "",
      currentTime: new Date().getHours(),
      weekDays: ["日", "一", "二", "三", "四", "五", "六"],
      months: Array.from({
        length: 12
      }, (_, i) => `${i + 1}月`),
      calendarDays: [],
      selectedDay: null,
      events: [],
      isDropdownVisible: false,
      params: {
        pageSize: 999,
        pageNum: 1,
        month: new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
      },
      touchStartX: 0,
      touchEndX: 0,
      transitionName: 'calendar-slide-right', // 默认向右滑动动画
      calendarKey: 0 // 用于强制重新渲染
    };
  },
  computed: {},
  onLoad() {
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonthIndex = today.getMonth();
    const date = today.getDate();

    this.selectedDay = {
      date: date,
      year: currentYear,
      month: currentMonthIndex,
      events: [],
    };

    this.loadMonthData();
  },
  onShow() {
    this.loadMonthData();
  },
  methods: {
    loadMonthData() {
      scheduleList(this.params).then(res => {
        this.events = [];
				console.log(11,res);
        res.data.rows.forEach((item, index) => {
          const eventItem = {
            date: {
              year: item.startDate.slice(0, 4) * 1,
              month: item.startDate.slice(5, 7) - 1,
              date: item.startDate.slice(8, 10) * 1
            },
            startTime: item.startTime.slice(11, 16),
            endTime: item.endTime.slice(11, 16),
            content: item.title,
            id: item.id
          };
          this.events.push(eventItem);
        });

        this.updateCalendar();

        if (this.selectedDay) {
          this.selectedDay.events = [];
          this.events.forEach((event) => {
            if (
              event.date.year === this.selectedDay.year &&
              event.date.month === this.selectedDay.month &&
              event.date.date === this.selectedDay.date
            ) {
              this.selectedDay.events.push(event);
            }
          });
        }
      });
    },
    addNew() {
      uni.navigateTo({
        url: '/pages/schedule/detail'
      })
    },
    clickEvent(id) {
      uni.navigateTo({
        url: `/pages/schedule/detail?id=${id}`
      })
    },
    toggleDropdown() {
      this.isDropdownVisible = !this.isDropdownVisible;
    },
    isSelectedDay(day) {
      return (
        this.selectedDay &&
        day.date === this.selectedDay.date &&
        day.month === this.selectedDay.month &&
        day.year === this.selectedDay.year
      );
    },
    fillPreviousMonthDays(currentDate, week) {
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth();
      const prevMonth = month === 0 ? 11 : month - 1;
      const prevYear = prevMonth === 11 ? year - 1 : year;

      const prevMonthLastDay = new Date(year, month, 0).getDate();
      const startDayIndex = currentDate.getDay();

      for (let i = 0; i < startDayIndex; i++) {
        const dateNum = prevMonthLastDay - (startDayIndex - i - 1);
        const dayObj = {
          date: dateNum,
          year: prevYear,
          month: prevMonth,
          events: [],
        };

        this.events.forEach((event) => {
          if (
            event.date.year === prevYear &&
            event.date.month === prevMonth &&
            event.date.date === dateNum
          ) {
            dayObj.events.push(event);
          }
        });

        week.push(dayObj);
      }
    },
    updateCalendar() {
      const firstDay = new Date(this.currentYear, this.currentMonthIndex, 1);
      const lastDay = new Date(this.currentYear, this.currentMonthIndex + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startDayIndex = firstDay.getDay();

      let week = [];
      this.calendarDays = [];

      // 补充上个月的天数
      this.fillPreviousMonthDays(firstDay, week);

      // 填充本月的每一天
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(this.currentYear, this.currentMonthIndex, i);
        const dayObj = {
          date: i,
          year: date.getFullYear(),
          month: date.getMonth(),
          events: [],
        };

        // 筛选当天事件
        this.events.forEach((event) => {
          if (
            event.date.year === dayObj.year &&
            event.date.month === dayObj.month &&
            event.date.date === dayObj.date
          ) {
            dayObj.events.push(event);
          }
        });

        week.push(dayObj);

        // 每满 7 天换行
        if (week.length % 7 === 0) {
          this.calendarDays.push(week);
          week = [];
        }
      }

      // 补充下个月的天数
      if (week.length > 0 && week.length < 7) {
        const remainingDays = 7 - week.length;
        const nextMonth = this.currentMonthIndex === 11 ? 0 : this.currentMonthIndex + 1;
        const nextYear =
          this.currentMonthIndex === 11 ? this.currentYear + 1 : this.currentYear;

        for (let i = 1; i <= remainingDays; i++) {
          const dayObj = {
            date: i,
            year: nextYear,
            month: nextMonth,
            events: [],
          };

          this.events.forEach((event) => {
            if (
              event.date.year === nextYear &&
              event.date.month === nextMonth &&
              event.date.date === i
            ) {
              dayObj.events.push(event);
            }
          });

          week.push(dayObj);
        }

        this.calendarDays.push(week);
      } else if (week.length > 0) {
        this.calendarDays.push(week);
      }

      this.currentMonth = this.currentYear + "." + (this.currentMonthIndex + 1);
    },
    prevMonth() {
      this.transitionName = 'calendar-slide-right';
      this.calendarKey++; // 强制重新渲染

      if (this.currentMonthIndex === 0) {
        this.currentYear--;
        this.currentMonthIndex = 11;
      } else {
        this.currentMonthIndex--;
      }

      this.selectedDay = null;
      this.params.month = this.currentYear + '-' + (this.currentMonthIndex + 1);
      this.loadMonthData();
    },
    nextMonth() {
      this.transitionName = 'calendar-slide-left';
      this.calendarKey++; // 强制重新渲染

      if (this.currentMonthIndex === 11) {
        this.currentYear++;
        this.currentMonthIndex = 0;
      } else {
        this.currentMonthIndex++;
      }

      this.selectedDay = null;
      this.params.month = this.currentYear + '-' + (this.currentMonthIndex + 1);
      this.loadMonthData();
    },
    changeMonth(index) {
      this.transitionName = index > this.currentMonthIndex ? 'calendar-slide-left' : 'calendar-slide-right';
      this.calendarKey++; // 强制重新渲染

      this.currentMonthIndex = index;
      this.selectedDay = null;
      this.params.month = this.currentYear + '-' + (this.currentMonthIndex + 1);
      this.loadMonthData();
      this.isDropdownVisible = false;
    },
    isToday(day) {
      const today = new Date();
      return (
        day.year === today.getFullYear() &&
        day.month === today.getMonth() &&
        day.date === today.getDate()
      );
    },
    hasEvent(day) {
      return day.events && day.events.length > 0;
    },
    selectDay(day) {
      this.selectedDay = day;
    },
    getWeekday(day) {
      const date = new Date(day.year, day.month, day.date);
      const weekday = date.getDay();
      return this.weekDays[weekday];
    },
    isCurrentMonthDay(day) {
      return day.year === this.currentYear && day.month === this.currentMonthIndex;
    },
    onTouchStart(e) {
      this.touchStartX = e.touches[0].clientX;
    },
    onTouchEnd(e) {
      this.touchEndX = e.changedTouches[0].clientX;
      const deltaX = this.touchEndX - this.touchStartX;
      const threshold = 50; // 滑动阈值

      if (deltaX > threshold) {
        // 向右滑动，切换到上一个月
        this.prevMonth();
      } else if (deltaX < -threshold) {
        // 向左滑动，切换到下一个月
        this.nextMonth();
      }
    }
  },
};
</script>

<style lang='scss' scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@800;900&display=swap');

body {
  font-family: 'Inter', sans-serif;
  font-weight: 900;
}

@import '../../style/documentmanage.scss';

.arrowImg {
  width: 15.34px;
  height: 15.34px;
}

.uni-button {
  background-color: none !important;
}

::v-deep .uni-button:after {
  border: none !important;
}

.is-other-month .date-number {
  color: #999;
  opacity: 0.6;
}

.is-other-month:hover {
  background-color: transparent !important;
  cursor: default;
}

.calendar-day .event-marker {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 6px;
  height: 6px;
  background-color: red;
  border-radius: 50%;
  z-index: 2;
}

.schedule-container {
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.calendar-section {
  width: 100%;
  padding-bottom: 20px;
  border-right: none;
}

.month-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  padding: 10px;
}

.el-dropdown-link {
  font-size: 15px;
  color: #555;
}

.week-header {
  display: flex;
  align-items: center;
  justify-content: space-around;
  background: #F5F5F5;
  height: 50px;
  border-bottom: 1px solid #E3E3E3;
}

.week-header text {
  text-align: center;
  flex: 1;
  background: #F5F5F5;
}

.calendar-days-wrapper {
  position: relative;
  overflow: hidden;
  height: 252px;
  /* 6行7列的高度 */
}

.calendar-days {
  position: absolute;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  background: #F5F5F5;
}

.calendar-week {
  display: flex;
  width: 100%;
}

.calendar-day {
  position: relative;
  width: calc(100% / 7);
  height: 42px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid transparent;
  transition: background-color 0.3s ease;
}

.calendar-day.is-selected .date-number {
  border-radius: 50%;
  background-color: #2D75D7;
  color: white;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: auto;
}

.calendar-day:hover .date-number:not(.is-selected .date-number) {
  border-radius: 50%;
  background-color: #f5f7fa;
  color: #333;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: auto;
  font-weight: normal;
}

.calendar-day .date-number {
  z-index: 1;
}

.schedule-details-section {
  width: 100%;
  padding: 10px 10px;
  overflow-y: auto;
  max-height: calc(100vh - 250px);
  box-sizing: border-box;
}

.schedule-event {
  border: 1px solid #ebeef5;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  background: #F8F8F8;
  display: flex;
}

.event-content {
  display: flex;
  align-items: center;
}

.event-time-wrapper {
  display: flex;
  flex-direction: column;
  margin-right: 20px;
  align-items: center;
  justify-content: center;
}

.event-start-time {
  color: #999;
  font-size: 13px;
  margin-bottom: 5px;
}

.event-end-time {
  color: #999;
  font-size: 13px;
}

.event-content {
  font-weight: 400;
  font-size: 14px;
  color: #999999;
}

.uni-dropdown {
  position: relative;
}

.uni-dropdown-menu {
  position: absolute;
  top: 120%;
  left: 0;
  background-color: white;
  border: 1px solid #ccc;
  z-index: 100;
  width: 65px;
}

.uni-dropdown-item {
  padding: 5px 10px;
  cursor: pointer;
  text-align: center;
}

.uni-dropdown-item:hover {
  background-color: #f5f7fa;
}

.addNew {
  width: 64px;
  height: 64px;
  background: #2D75D7;
  border-radius: 50%;
  color: #fff;
  font-size: 18px;
  position: fixed;
  right: 3%;
  bottom: 10%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 日历滑动动画 - 向左滑动（下一个月） */
.calendar-slide-left-enter-active {
  animation: slideInFromRight 0.3s ease-out;
}

.calendar-slide-left-leave-active {
  animation: slideOutToLeft 0.3s ease-out;
}

/* 日历滑动动画 - 向右滑动（上一个月） */
.calendar-slide-right-enter-active {
  animation: slideInFromLeft 0.3s ease-out;
}

.calendar-slide-right-leave-active {
  animation: slideOutToRight 0.3s ease-out;
}

@keyframes slideInFromRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slideOutToLeft {
  from {
    transform: translateX(0);
    opacity: 1;
  }

  to {
    transform: translateX(-100%);
    opacity: 0;
  }
}

@keyframes slideInFromLeft {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slideOutToRight {
  from {
    transform: translateX(0);
    opacity: 1;
  }

  to {
    transform: translateX(100%);
    opacity: 0;
  }
}

.outbottom {
	margin-top: 88rpx;
}
</style>